package com.jf.ai.service;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.Generation;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.PromptTemplate;
import org.springframework.ai.converter.MapOutputConverter;
import org.springframework.ai.deepseek.DeepSeekChatModel;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2025-06-13
 * Time:14:10
 */
@Service
public class MapStructService {
    private final ChatClient chatClient;
    private final ChatModel chatModel;

    public MapStructService(ChatClient.Builder builder, DeepSeekChatModel deepSeekChatModel) {
        this.chatClient = builder.build();
        this.chatModel = deepSeekChatModel;
    }

    public Map<String, Object> getMapChatClient(String key) {
        Map<String, Object> map = chatClient.prompt()
                .user(u -> u.text("Provide me a List of {subject}")
                        .param("subject", "an array of numbers from 1 to 9 under they key name 'numbers'"))
                .call()
                .entity(new ParameterizedTypeReference<>() {});
        return map;
    }

    public Map<String, Object> getMapByChatModel(String key) {
        MapOutputConverter converter = new MapOutputConverter();

        String format = converter.getFormat();

        String template = """
                Provide me a List of {subject}
                {format}
                """;

        Generation generation = chatModel.call(PromptTemplate.builder()
                        .template(template)
                        .variables(Map.of("subject", "an array of numbers from 1 to 9 under they key name 'numbers'", "format", format))
                        .build().create())
                .getResult();
        Map<String, Object> map = converter.convert(Objects.requireNonNull(generation.getOutput().getText()));
        return map;
    }
}
